#include <iostream>
#include "add_contact.pb.h"
#include "ContactException.hpp"
#include <string>
#include "httplib.h"
#include "UUIDUtil.hpp"

using namespace httplib;
using namespace ns_uuid;
using std::cout;
using std::endl;



void PrintContacts(Add_http_contacts::AddContactRequest& request)
{
        std::cout << "联系人姓名：" << request.name() << std::endl;
        std::cout << "联系人年龄：" << request.age() << std::endl;
        for(int j = 0;j<request.phone_size();j++)
        {
            const Add_http_contacts::AddContactRequest_Phone phone = request.phone(j);
            std::cout << "联系人电话" << j+1  << ": "<< phone.num() << "   ";
            std::cout << "电话类型"  << ": ("<< AddContactRequest_Phone_PhoneType_Name(phone.type()) << ")" << std::endl; 
        }
}
int main()
{
    Server server;
    server.Post("/contacts/add", [](const Request &req, Response &resp)
        {
            // 反序列化request : req.body
            Add_http_contacts::AddContactRequest request;
            Add_http_contacts::AddContactResponse response;
            try
            {
                if (!request.ParseFromString(req.body))
                {
                    throw ContactException("request反序列化失败");
                }

                //新增联系人，持久化存储——————这里只是实现打印
                PrintContacts(request);

                // 序列化response
                response.set_success(true);
                
                response.set_uuid(UUIDUtil::uuid());
                std::string resp_str;
                if (!response.SerializeToString(&resp_str))
                {
                    throw ContactException("response序列化失败");
                }
                resp.status = 200;
                resp.body = resp_str;
                resp.set_header("Content-Type", "application/protobuf");
            }
            catch (const ContactException &e)
            {
                resp.status = 500;
                response.set_success(false);
                response.set_error_desc(e.What());
                std::string resp_str;
                if (response.SerializeToString(&resp_str))
                {
                    resp.body = resp_str;
                    resp.set_header("Content-Type", "application/protobuf");
                }
            }
        });

    server.listen("0.0.0.0", 8888);
    return 0;
}